<?php

namespace app\admin\model\video;

use think\Config;
use think\Model;
use think\Log;

class Order extends Model
{

    

    

    // 表名
    protected $name = 'video_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'paytime_text',
        'status_text'
    ];
    

    
    public function getStatusList()
    {
        return ['created' => __('待支付'), 'paid' => __('已支付')];
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function video()
    {
        return $this->belongsTo('app\admin\model\video\Video', 'video_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 视频分佣
     */
    public static function VideoCommission($order_id)
    {
        $order = self::getByOrderId($order_id);
        if (!$order) {
            return false;
        }

        $user = \think\Db::name('user')->where('id', $order['user_id'])->where('status', 'normal')->find();
        if ($user) {
            $parent_user = \think\Db::name('user')->where('id', $user['pid'])->where('status', 'normal')->find();
            if ($parent_user){
                //分佣比例
                if ($parent_user['commission_rate']>0){
                    $commission_rate = $parent_user['commission_rate']>0;
                }else{
                    $commission_rate = Config::get('site.commission_rate');
                }
                $commission_rate = bcMath($commission_rate,100,'/');
                $price = bcMath($order->amount,$commission_rate,'*');
                $memo = '视频推广分佣 比例'.$commission_rate.'% <br/>订单编号:'.$order_id;
                Log::info('视频推广分佣:'.$memo);
                //给到余额
                \app\common\model\User::money($price,$parent_user['id'],$memo,5);
//                $parent_user->setInc('cumulative_gain',$price);
                // \think\Db::name('user')->where('id', $parent_user['id'])->setInc('cumulative_gain',$price);
                return true;
            }

        }


        return false;
    }
}
